package com.sntk.registermanager.staff.application.service;

import com.sntk.registermanager.common.exception.ObjectNotExistException;
import com.sntk.registermanager.common.infrastructure.resp.OperatorInfo;
import com.sntk.registermanager.common.utils.FileUtil;
import com.sntk.registermanager.staff.application.dto.DoctorInfoCreator;
import com.sntk.registermanager.staff.application.dto.DoctorInfoUpdator;
import com.sntk.registermanager.staff.domain.event.UserAddEvent;
import com.sntk.registermanager.staff.domain.model.Affiliation;
import com.sntk.registermanager.staff.domain.model.DoctorInfo;
import com.sntk.registermanager.staff.domain.model.Gender;
import com.sntk.registermanager.staff.domain.model.User;
import com.sntk.registermanager.staff.domain.repository.DoctorInfoRepository;
import com.sntk.registermanager.staff.infrastructure.commit.AffiliationCommit;
import com.sntk.registermanager.staff.infrastructure.commit.impl.UserCommitConvert;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author liuyunxia
 */
@Service
public class DoctorInfoService {

    @Autowired
    private DoctorInfoRepository doctorInfoRepository;
    @Autowired
    private UserCommitConvert userCommitConvert;
    @Autowired
    private ApplicationEventPublisher publisher;
    @Autowired
    private AffiliationCommit affiliationCommit;

    /**
     * 添加医生信息
     * @param creator
     * @param operatorInfo
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    public void addDoctor(DoctorInfoCreator creator, OperatorInfo operatorInfo){

        String institutionNumber = operatorInfo.getInstitutionNumber();
        Affiliation affiliation = affiliationCommit.searchAffiliation(institutionNumber);
        if(affiliation == null){
            throw new ObjectNotExistException("机构不存在!");
        }
        affiliation.normalException();

        User user = userCommitConvert.searchUser(creator.getUname());
        String doctorCode = doctorInfoRepository.generateDoctorCode();
        //图片处理
        String imgSrc = "asf";
//        try {
//            //
//            imgSrc = saveImg(creator.getImg(),doctorCode);
//        } catch (Exception e) {
//            //上传图片失败
//            e.printStackTrace();
//        }
        DoctorInfo doctorInfo = DoctorInfo.addDoctor(doctorCode,creator.getDoctorName(),
                creator.getPhone(),creator.getIntroduction(),creator.getRemark(),
                creator.getJobTitle(), Gender.get(creator.getGender()),creator.getUname(),
                imgSrc);

        doctorInfoRepository.add(doctorInfo,operatorInfo.getOperator());
        if(user == null){
            //添加用户
//            publisher.publishEvent(new UserAddEvent(new User(creator.getUname(),creator.getDoctorName(),false),institutionNumber,
//                    creator.getPassword(),creator.getPhone(), 1,null,operatorInfo));
            userCommitConvert.addUser(new UserAddEvent(new User(creator.getUname(),creator.getDoctorName(),false),institutionNumber,
                    creator.getPassword(),creator.getPhone(), 1,null,operatorInfo));
        }
    }



    /**
     * 修改医生信息
     * @param doctoeCode
     * @param updator
     * @param operatorInfo
     */
    @Transactional(rollbackFor = Exception.class)
    public void modify(String doctoeCode, DoctorInfoUpdator updator, OperatorInfo operatorInfo){
        DoctorInfo doctorInfo = doctorInfoRepository.findByKey(doctoeCode);
        if(doctorInfo == null){
            throw new ObjectNotExistException("医生信息不存在!");
        }
        doctorInfo.normalException();
        doctorInfo.modify(updator.getDoctorName(),updator.getPhone(),updator.getIntroduction(),updator.getRemark(),
                updator.getJobTitle(), Gender.get(updator.getGender()));
        doctorInfoRepository.add(doctorInfo,operatorInfo.getOperator());
    }

    /**
     * 禁用
     * @param doctoeCode
     * @param operatorInfo
     */
    @Transactional(rollbackFor = Exception.class)
    public void disabled(String doctoeCode, OperatorInfo operatorInfo){
        DoctorInfo doctorInfo = doctorInfoRepository.findByKey(doctoeCode);
        if(doctorInfo == null){
            throw new ObjectNotExistException("医生信息不存在!");
        }
        doctorInfo.disable();
        doctorInfoRepository.add(doctorInfo,operatorInfo.getOperator());
    }

    /**
     * 启用
     * @param doctoeCode
     * @param operatorInfo
     */
    @Transactional(rollbackFor = Exception.class)
    public void enable(String doctoeCode, OperatorInfo operatorInfo){
        DoctorInfo doctorInfo = doctorInfoRepository.findByKey(doctoeCode);
        if(doctorInfo == null){
            throw new ObjectNotExistException("医生信息不存在!");
        }
        doctorInfo.enable();
        doctorInfoRepository.add(doctorInfo,operatorInfo.getOperator());
    }


    /**
     * 修改照片
     * @param doctorCode
     * @param multipartFile
     */
    @Transactional(rollbackFor = Exception.class)
    public void modityDoctorImg(String doctorCode, MultipartFile multipartFile){
        //测试
        try {
            deteleImg(doctorCode);
            saveImg(multipartFile, doctorCode);
        }catch (Exception e){
           e.printStackTrace();
        }

    }

    //删除照片
    public void deteleImg(String doctorCode) throws Exception {
        String tName = "doctor" + doctorCode;
        FileUtil.deleteFile(tName);
    }

//    public static boolean isImage(
//            MultipartFile imageFile) {
//        if (!imageFile.exists()) {
//            return false;
//        }
//        Image img = null;
//        try {
//            img = ImageIO.read(imageFile);
//            if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {
//                return false;
//            }
//            return true;
//        } catch (Exception e) {
//            return false;
//        } finally {
//            img = null;
//        }
//    }

    //上传图片
    public String saveImg(MultipartFile multipartFile, String doctorCode) throws Exception {
        String fileName = multipartFile.getOriginalFilename();
        //后缀名(判断)
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        File file = multipartFileToFile(multipartFile);
        String tName = "doctor" + doctorCode;
        //图片写入服务器
        String imgName = FileUtil.copyFile(file, tName);
        return imgName;
    }

    public File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile;
        if(file.equals("") || file.getSize() <= 0){
            return null;
        }else {
            InputStream ins;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = ins.read(buffer, 0, 1024)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
